<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\SmsRechargeConfigModel;
use app\admin\model\SmsRechargeLogModel;
use app\admin\model\SmsSendLogModel;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use fast\Random;
use think\Db;
use think\Exception;
use think\Hook;

/**
 * 手机短信接口
 */
class Sms extends Api
{
    protected $noNeedLogin = ['send','check'];
    protected $noNeedRight = '*';

    /**
     * 发送验证码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $event 事件名称
     */
    public function send()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ? $event : 'register';

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        if (!Hook::get('sms_send')) {
            $this->error(__('请在后台插件管理安装短信验证插件'));
        }
        $ret = Smslib::send($mobile, null, $event);
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
        }
    }

    /**
     * 检测验证码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $event 事件名称
     * @param string $captcha 验证码
     */
    public function check()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ? $event : 'register';
        $captcha = $this->request->post("captcha");

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        $ret = Smslib::check($mobile, $captcha, $event);
        if ($ret) {
            $this->success(__('成功'));
        } else {
            $this->error(__('验证码不正确'));
        }
    }


    public function recharge_config()
    {
        $list = SmsRechargeConfigModel::order('num','asc')
            ->field('id,num,money,score')
            ->select();
        $this->success('成功', $list);
    }


    public function recharge()
    {
        $id = $this->request->param('id/d', 0);
        $config_info = SmsRechargeConfigModel::get($id);
        if (empty($config_info)) $this->error('数据不存在');

        Db::startTrans();
        try {
            $order_no = date('YmdHis') . Random::numeric(6);
            $use_score = min($this->auth->score, $config_info['score']);
            $score_money = config('site.score_money');
            $pay_money = $config_info['money'];
            if ($score_money && $use_score) {
                $scoreToMoney = bcdiv($use_score, $score_money, 2);
                $pay_money = bcsub($pay_money, $scoreToMoney, 2);
            }
            // 最少1分钱
            $pay_money = max(0.01, $pay_money);
            $recharge = SmsRechargeLogModel::create([
                'order_no' => $order_no,
                'user_id' => $this->auth->id,
                'money' => $config_info['money'],
                'pay_money' => $pay_money,
                'score' => $use_score,
                'rid' => $id,
                'able_num' => $config_info['num'],
            ]);
            \app\common\model\User::score(-1 * $use_score, $this->auth->id, '购买短信', 6);
            //回调链接
            $notifyurl = $this->request->root(true) . '/api/notify/sms_pay_success';
            $amount = $pay_money;
            $title = '购买短信';
            $method = 'miniapp';
            $openid = $this->auth->openid;
            if (empty($openid)) throw new Exception('请先绑定小程序');
            $data = Service::submitOrder($amount, $order_no, 'wechat', $title, $notifyurl, '', $method, $openid);
            $data['recharge_id'] = $recharge->id;
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('success', $data ?? []);
    }

    public function cancel_recharge()
    {
        $recharge_id = $this->request->param('recharge_id/d', 0);
        if ($recharge_id < 1) {
            $this->error('recharge_id错误');
        }
        $recharge_log = SmsRechargeLogModel::get($recharge_id);
        if (empty($recharge_log)) $this->error('数据不存在');
        // 已支付、已取消的不处理
        if ($recharge_log->status == 1 || $recharge_log->status == 2) {
            $this->success();
        }
        Db::startTrans();
        try {

            \app\common\model\User::score($recharge_log->score, $this->auth->id, '购买短信取消，积分退回', 6);

            $recharge_log->status = 2;
            $recharge_log->save();
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('success');
    }

    public function send_log()
    {
        $page_size = $this->request->param('page_size', 10);
        $kw = $this->request->param('kw', '');
        $where = [];
        if (!empty($kw)) {
            $where['content|mobile'] = ['like', '%' . $kw . '%'];
        }
        $list = SmsSendLogModel::where('user_id', $this->auth->id)
            ->where($where)
            ->field('id,content,mobile,create_time')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['create_time_text']);
            });

        $this->success('success', $list);
    }

}
